package com.szlanyou.thirdsdk.retrofit.client;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author 陈章
 * create at： 2020/11/5 8:42
 * desc: 用于GET、POST统一的URL参数添加
 */
public class ClientCommonParamsManager implements IClientCommonParamsManage {
    private Map<String, Object> params = new LinkedHashMap<>();
    private Map<String, Object> headers = new LinkedHashMap<>();
    private OnCommonParamsChangeListener onParamsChangeListener;
    private OnRequestBodyInterceptListener onRequestBodyInterceptListener;

    protected ClientCommonParamsManager() {
    }

    public boolean isEmpty() {
        return params.isEmpty();
    }

    public Map<String, Object> getCommonParams() {
        return params;
    }

    public Map<String, Object> getCommonHeaders() {
        return headers;
    }

    @Override
    public void addCommonParam(String key, Object value) {
        this.params.put(key, value);
        if (this.onParamsChangeListener != null) {
            this.onParamsChangeListener.onCommonParamsChange(this.params);
        }
    }

    @Override
    public void removeCommonParam(String key) {
        this.params.remove(key);
        if (this.onParamsChangeListener != null) {
            this.onParamsChangeListener.onCommonParamsChange(this.params);
        }
    }

    @Override
    public void addCommonHeader(String key, Object value) {
        this.headers.put(key, value);
        if (this.onParamsChangeListener != null) {
            this.onParamsChangeListener.onCommonParamsChange(this.headers);
        }
    }

    @Override
    public void removeCommonHeader(String key) {
        this.headers.remove(key);
        if (this.onParamsChangeListener != null) {
            this.onParamsChangeListener.onCommonParamsChange(this.headers);
        }
    }


    public void setOnCommonParamsChangeListener(OnCommonParamsChangeListener onParamsChangeListener) {
        this.onParamsChangeListener = onParamsChangeListener;
    }

    public OnRequestBodyInterceptListener getOnRequestBodyInterceptListener() {
        return onRequestBodyInterceptListener;
    }

    @Override
    public void setOnRequestBodyInterceptListener(OnRequestBodyInterceptListener onRequestBodyInterceptListener) {
        this.onRequestBodyInterceptListener = onRequestBodyInterceptListener;
    }

    public interface OnCommonParamsChangeListener {
        /**
         * Param参数发生变化
         *
         * @param map
         */
        void onCommonParamsChange(Map<String, Object> map);

        /**
         * Header参数发生变化
         *
         * @param map
         */
        void onCommonHeaderChange(Map<String, Object> map);
    }

    /**
     * 由于有些加密的算法需要使用到已经设置的Header字段
     * 监听Header的拦截用于实时的设置计算出来的Header
     */
    public interface OnRequestBodyInterceptListener {
        /**
         * 拦截 body
         * @param bodyJson body的JSON串
         */
        void onRequestBodyIntercept(String bodyJson);
    }
}